package com.cmw.auntapp.core.util;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Process;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import java.io.File;
import java.util.Locale;

import androidx.core.content.FileProvider;

/**
 * Created by Administrator on 2016/8/18.
 */
public class CommonUtil {

    /**
     * 判断应用是否安装
     *
     * @param context
     * @param packageName
     * @return
     */
    public static boolean checkInstalled(Context context, String packageName) {
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo packageInfo = pm.getPackageInfo(packageName, 0);
            if (packageInfo != null) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 获取apk包的信息：版本号，名称，图标等
     * @param apkPath apk包的绝对路径
     * @param context
     */
    public static PackageInfo apkInfo(String apkPath, Context context) {
        if (!(apkPath.endsWith(".apk") && FileUtil.isFileExist(apkPath))) {
            return null;
        }

        PackageManager pm = context.getPackageManager();
        PackageInfo pkgInfo = pm.getPackageArchiveInfo(apkPath,PackageManager.GET_ACTIVITIES);

        return pkgInfo;
    }



    public static int getVersionByPackage(Context context, String packageName) {
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo packageInfo = pm.getPackageInfo(packageName, 0);
            if (packageInfo != null) {
                return packageInfo.versionCode;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static void installApk(String savePath) {
        File file = new File(savePath);
        if (file.exists() && file.length() > 0) {
            ShellUtils.CommandResult result = ShellUtils.execCommand("pm install -r " + savePath, false);
            Log.e("installApk", "result" + result.successMsg);
//            Intent intent = new Intent("com.xgimi.settings.APPINSTALL");
//            intent.putExtra("package_Path", savePath);
//            App.getInstance().sendBroadcast(intent);
        }
    }

    // 自动安装apk包
    public static void  updateAPK(Context context, File file) {
        if (context == null) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //安卓7.0以上需要在在Manifest.xml里的application里，设置provider路径
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, "com.cmw.auntapp.fileprovider", new File(file.getPath()));
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    public static void openFile(Context context, String savePath) {
        try {
            File file = new File(savePath);
            if (!file.exists()) {
                return;
            }
            String mimetype = getMimeType(file);
            Intent intent = new Intent("android.intent.action.VIEW");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(file);
            intent.setDataAndType(uri, mimetype);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static String getSuffix(File file) {
        if (file == null || !file.exists() || file.isDirectory()) {
            return null;
        }
        String fileName = file.getName();
        if (fileName.equals("") || fileName.endsWith(".")) {
            return null;
        }
        int index = fileName.lastIndexOf(".");
        if (index != -1) {
            return fileName.substring(index + 1).toLowerCase(Locale.US);
        } else {
            return null;
        }
    }

    public static String getMimeType(File file) {
        String suffix = getSuffix(file);
        if (suffix == null) {
            return "file/*";
        }
        String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(suffix);
        if (type != null || !type.isEmpty()) {
            return type;
        }
        return "file/*";
    }

    public static String getMimeType(String filePath) {
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        String mime = "text/plain";
        if (filePath != null) {
            try {
                mmr.setDataSource(filePath);
                mime = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE);
            } catch (IllegalStateException e) {
                return mime;
            } catch (IllegalArgumentException e) {
                return mime;
            } catch (RuntimeException e) {
                return mime;
            }
        }
        return mime;
    }

    public static String formatDuration(long duration) {
        long time = duration / 1000;
        if (time <= 0) {
            return "00:00:00";
        }
        long min = time / 60 % 60;
        long hour = time / 60 / 60;
        long second = time % 60;
        return String.format("%02d:%02d:%02d", hour, min, second);
    }


    public static void setCurrentVolume(int percent, Context mc) {
        AudioManager am = (AudioManager) mc.getSystemService(Context.AUDIO_SERVICE);
        int maxvolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        am.setStreamVolume(AudioManager.STREAM_MUSIC, (maxvolume * percent) / 100,
                AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
        am.setMode(AudioManager.MODE_INVALID);
    }

    public static void setVolumeMute(Context mc) {
        AudioManager am = (AudioManager) mc.getSystemService(Context.AUDIO_SERVICE);
        am.setStreamMute(AudioManager.STREAM_MUSIC, true);
    }

    public static void setVolumeUnmute(Context mc) {
        AudioManager am = (AudioManager) mc.getSystemService(Context.AUDIO_SERVICE);
        am.setStreamMute(AudioManager.STREAM_MUSIC, false);
    }

    public static void showToask(Context context, String tip) {
        Toast.makeText(context, tip, Toast.LENGTH_SHORT).show();
    }

    public static int getScreenWidth(Context context) {
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        return display.getWidth();
    }

    public static int getScreenHeight(Context context) {
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        return display.getHeight();
    }

    public static ViewSize getFitSize(Context context, MediaPlayer mediaPlayer) {
        int videoWidth = mediaPlayer.getVideoWidth();
        int videoHeight = mediaPlayer.getVideoHeight();
        double fit1 = videoWidth * 1.0 / videoHeight;

        int width2 = getScreenWidth(context);
        int height2 = getScreenHeight(context);
        double fit2 = width2 * 1.0 / height2;

        double fit = 1;
        if (fit1 > fit2) {
            fit = width2 * 1.0 / videoWidth;
        } else {
            fit = height2 * 1.0 / videoHeight;
        }

        ViewSize viewSize = new ViewSize();
        viewSize.width = (int) (fit * videoWidth);
        viewSize.height = (int) (fit * videoHeight);

        return viewSize;
    }

    public static class ViewSize {
        public int width = 0;
        public int height = 0;
    }


    public static void deleteAll(File file) {

        if (file.exists() && file.list().length != 0) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                files[i].delete();
            }
            if (file.exists())         //如果文件本身就是目录 ，就要删除目录
                file.delete();
        }
    }

}
